package com.jhws.core.log.bo;

import com.jhws.common.JHServletResponseWrapper;
import com.jhws.common.PropertiesReader;
import com.jhws.util.LogHelper;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    /**
     * 通过web.xml中的filter mapping限制.x Web请求和/api请求进入
     *
     * 将所有请求的参数与返回值打印出来，只有trace等级才会打印
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            String accept = ((HttpServletRequest) request).getHeader("Accept");
            String contentType = request.getContentType();
            contentType = contentType != null ?contentType:"";
            accept = accept == null?"":accept;
            if (PropertiesReader.getProperty("logLevel").equals("trace") && !contentType.startsWith("multipart/form-data")) {
                ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);

                JHServletResponseWrapper contentCachingResponseWrapper = new JHServletResponseWrapper((HttpServletResponse) response);

                chain.doFilter(contentCachingRequestWrapper, accept.startsWith("image") ? response : contentCachingResponseWrapper);

                String content = ((HttpServletRequest) request).getQueryString();
                if (((HttpServletRequest) request).getMethod().equalsIgnoreCase("POST"))
                    content = new String(contentCachingRequestWrapper.getContentAsByteArray());

                String responseContentStr = "图片格式省略数据";
                byte[] responseContent = null;
                if (!accept.startsWith("image")) {
                    responseContent = contentCachingResponseWrapper.getDataStream();
                    responseContentStr = responseContent.length > 0 ? new String(responseContent, "UTF-8") : "none";
                }
                //if(contentType != null && contentType.startsWith("application/json")) {
                String requestMsg = "[HTTP Request] \n" +
                        "              [URI] " + ((HttpServletRequest) request).getRequestURI() + "\n" +
                        "              [params] " + (content != null && content.length() > 0 ? content : "none") + "\n" +
                        "              [response] " + responseContentStr;

                LogHelper.t(requestMsg);
                if (responseContent != null && responseContent.length > 0)
                    contentCachingResponseWrapper.getWriter().write(responseContentStr);
            } else
                chain.doFilter(request, response);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void destroy() {

    }
}
